package com.ctvit.breadking.news.baidu.service.impl;

import com.ctvit.breadking.news.baidu.service.VipTranslateService;
import com.ctvit.breadking.news.baidu.translate.TransApi;
import com.ctvit.breadking.news.core.solr.repository.SolrDocumentRepository;
import com.ctvit.breadking.news.task.pojo.entity.HttpLogEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.Date;

import static com.ctvit.breadking.news.core.constant.CommonConstant.FIELD_CREATE_TIME;

@Slf4j
@Service
public class VipTranslateServiceImpl implements VipTranslateService {

    private static final String APP_ID = "20241007002168627";

    private static final String SECURITY_KEY = "4PTmi2YErnrRyzBX6ajl";

    private final TransApi api = new TransApi(APP_ID, SECURITY_KEY);

    private final SolrDocumentRepository solrDocumentRepository;

    public VipTranslateServiceImpl(SolrDocumentRepository solrDocumentRepository) {
        this.solrDocumentRepository = solrDocumentRepository;
    }

    @Override
    public boolean translate(String text) {
        long requestTime=System.currentTimeMillis();
        String responseBody = api.getTransResult(text, "auto", "zh");
        log.info("responseBody=>"+responseBody);
        long responseTime=System.currentTimeMillis();

        SolrInputDocument solrDocument = assignHttpLogElement(HttpMethod.POST.name(), text, responseBody, requestTime, responseTime);
        solrDocumentRepository.add(HttpLogEntity.COLLECTION_HTTP_LOG, solrDocument.getFieldValue(HttpLogEntity.FIELD_ID).toString(), solrDocument);

        return true;
    }

    private SolrInputDocument assignHttpLogElement(String requestMethod, String requestBody, String responseBody, long requestTime, long responseTime) {
        SolrInputDocument solrDocument = new SolrInputDocument();
        solrDocument.addField(HttpLogEntity.FIELD_ID, "fanyi-api.baidu.com/api/trans/vip/translate_" + System.currentTimeMillis());
        solrDocument.addField(HttpLogEntity.FIELD_CODE, "fanyi-api.baidu.com/api/trans/vip/translate");
        solrDocument.addField(HttpLogEntity.FIELD_NAME, "百度翻译");
        solrDocument.addField(HttpLogEntity.FIELD_URL, TransApi.TRANS_API_HOST);
        solrDocument.addField(HttpLogEntity.FIELD_REQUEST_METHOD, requestMethod);
        solrDocument.addField(HttpLogEntity.FIELD_REQUEST_BODY, requestBody);
        solrDocument.addField(HttpLogEntity.FIELD_REQUEST_TIME, requestTime);
        solrDocument.addField(HttpLogEntity.FIELD_RESPONSE_BODY, responseBody);
        solrDocument.addField(HttpLogEntity.FIELD_RESPONSE_TIME, responseTime);
        solrDocument.addField(FIELD_CREATE_TIME, new Date());
        return solrDocument;
    }

}
